﻿using System;
using System.Net.Mime;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace CI.Utility
{
    public static class ResourceHelper
    {
        public static T LoadResource<T>(string path)
        {
            var c = default(T);

            var sri = Application.GetResourceStream(new Uri(path, UriKind.Relative));

            if (sri == null) throw new InvalidOperationException("Couldn't find resource : " + path);

            using (var stream = sri.Stream)
            {
                if (sri.ContentType == "application/xaml+xml")
                {
                    c = (T) XamlReader.Load(stream);
                }
                else if (sri.ContentType.IndexOf("image") >= 0)
                {
                    var bi = new BitmapImage();

                    bi.BeginInit();
                    bi.StreamSource = stream;
                    bi.EndInit();

                    if (typeof (T) == typeof (ImageSource))
                    {
                        c = (T) ((object) bi);
                    }
                    else if (typeof (T) == typeof (MediaTypeNames.Image))
                    {
                        var img = new Image {Source = bi};
                        c = (T) ((object) img);
                    }
                }
            }

            return c;
        }
    }
}